/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package org.flower.httprc.util;

import com.fasterxml.jackson.core.JsonFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.io.IOException;
import org.apache.commons.lang3.StringUtils;

/**
 *
 * @author ZhuYanXin
 */
public class JsonUtil {

    public static String formatJson(String json) {
        if (!validJson(json)) {
            return json;
        }
        JsonElement parse = JsonParser.parseString(json);
        Gson gson = new GsonBuilder()
                .setPrettyPrinting()
                .create();
        return gson.toJson(parse);
    }

    public static boolean validJson(String json) {
        if (StringUtils.isBlank(json)) {
            return false;
        }
        JsonFactory factory = new JsonFactory();
        try {
            com.fasterxml.jackson.core.JsonParser parser = factory.createParser(json);
            while (!parser.isClosed()) {
                parser.nextToken();
            }
        } catch (IOException ex) {
            return false;
        }
        return true;
    }
}
